package com.yc.javaee.servlet.d0615;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CookieServlet", value = "/cookie.s")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 浏览器会自动的将当前路径下的cookie值发送给服务器
        // 从请求对象中获取 cookie 数据
        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        if(cookies != null){
            PrintWriter out = response.getWriter();
            for (Cookie cookie : cookies) {
                out.append(cookie.getName()).append(" = ").append(cookie.getValue())
                .append("<br>");
            }
        }
        // 创建cookie对象
        Cookie cookie = new Cookie("book", "java");
        // 设置有效期: 单位:秒
        cookie.setMaxAge(60 * 60 * 24 * 7); // 该cookie在浏览器端保存 1 周
        // 如果没有设置 maxAge => 关闭浏览器时自动删除
        // 如果 maxAge = 0    => 浏览器接收到响应立即删除该 cookie
        // 添加 cookie 到响应对象
        response.addCookie(cookie);

        // 删除cookie
        cookie = new Cookie("gender", "man");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
